<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="uid">
        <el-input v-model="queryParams.uid" placeholder="请输入用户ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商户ID" prop="id">
        <el-input v-model="queryParams.infoId" placeholder="请输入商户ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商户名称" prop="infoName">
        <el-input v-model="queryParams.infoName" placeholder="请输入商户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="渠道名称" prop="channelName" class="single-line-label">
        <span class="label-spacing"></span>
        <el-select v-model="queryParams.channelName" clearable placeholder="请选择渠道名称" filterable default-first-option
                   allow-create @change="handleStatusChange">
          <el-option v-for="(item, i) in extData.channelNameList || []" :key="i" :label="item.key"
                     :value="item.key"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table v-loading="loading" :data="pushInfoList">
      <el-table-column label="用户ID" align="center" prop="uid" fixed-width="200">
        <template slot-scope="scope">
          <span class="clickable-uid" :style="{ color: getUidColor(scope.row.uid) }"
                @click="handleDetailsDialog(scope.row)">
            {{ scope.row.uid }}
          </span>
        </template>
      </el-table-column>



      <el-table-column label="机构名称" align="center" prop="infoName">
        <template slot-scope="scope">
          {{ scope.row.infoId }} | {{ scope.row.infoName }}
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="priceAmount" />
      <el-table-column label="渠道名称" align="center" prop="realname">
        <template slot-scope="scope">
          {{ scope.row.channelName }}
        </template>
      </el-table-column>

      <el-table-column label="所属地" align="center">
        <template slot-scope="scope">
          {{ scope.row.province }}--{{ scope.row.city }}
        </template>
      </el-table-column>

      <el-table-column label="授权地址" align="center" prop="pageUrl" width="300">
        <template slot-scope="scope">
          <a :href="scope.row.approveUrl" target="_blank" style="color: blue" class="blue-link">{{ scope.row.approveUrl
            }}</a>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status" />


      <el-table-column label="创建时间" align="center" width="135">
        <template slot-scope="scope">
          {{ formatTimestamp(scope.row.createTime) }}
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList" />

    <!-- 用户详情弹窗 -->
    <Member ref="MemberRef" />

  </div>
</template>

<style scoped>
.clickable-uid {
  cursor: pointer;
  color: blue;
}

.clickable-uid:hover {
  text-decoration: underline;
}
</style>

<script>
import { listApibPushInfo } from "@/api/merchant/pushApibInfo";
import { baseInfoExtData } from "@/api/source/baseInfo";
import Member from '@/views/member/memeber.vue';
export default {
  name: "PushInfo",
  components: {
    Member
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商户推送信息表格数据
      pushInfoList: [],
      // 弹出层标题
      title: "",
      extData: {},
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        priceAmount: null,
        uid: null,
        infoId: null,
        dateInfo: this.getDefaultDate(),
      },
      uidToColorMap: {}, // 新增：存储每个 UID 对应的颜色
      colorPool: [ // 精简且分明的颜色池
        '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF', '#FFA500', '#800080', '#008000'
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      infoId: ""
    };
  },
  created() {
    this.getList();
    this.getOptions();
    const thirtySeconds = 120 * 1000;
    setInterval(() => {
      this.getList();
    }, thirtySeconds);
  },

  methods: {
    getOptions() {
      baseInfoExtData().then((response) => {
        this.extData = response.data;
      });
    },
    assignUidColors() {
      const uniqueUids = [...new Set(this.pushInfoList.map(item => item.uid))]; // 获取唯一的 UID 列表
      let colorIndex = 0;

      // 遍历唯一的 UID，分配颜色
      uniqueUids.forEach(uid => {
        this.uidToColorMap[uid] = this.colorPool[colorIndex % this.colorPool.length]; // 循环使用颜色池
        colorIndex++;
      });
    },
    // 获取指定 UID 对应的颜色
    getUidColor(uid) {
      return this.uidToColorMap[uid] || '#000000';  // 如果没有分配颜色，默认为黑色
    },

    async handleDetailsDialog(row) {
      this.$refs.MemberRef.show(row.uid)
    },

    handleStatusChange(value) {
      console.log("Selected status:", value);
    },

    // 判断新数据
    isNewData(newData) {
      const previousPushInfoList = JSON.parse(localStorage.getItem('previousPushInfoList')) || [];
      return JSON.stringify(newData) !== JSON.stringify(previousPushInfoList);
    },

    // 获取数据并检查是否有新数据
    getList() {
      this.loading = true;
      listApibPushInfo(this.queryParams).then(response => {
        const newData = response.rows;
        this.pushInfoList = newData;
        this.total = response.total;

        if (this.isNewData(newData)) {
          this.triggerBrowserFlicker(); // 检测到新数据，触发浏览器闪烁
          this.showNotification('来活了', '都是链接'); // 显示通知并触发语音提示
        }

        localStorage.setItem('previousPushInfoList', JSON.stringify(newData));

        this.assignUidColors();
        this.loading = false;
      });
    },



    // 启动浏览器标签闪烁效果
    triggerBrowserFlicker() {
      let originalTitle = document.title;
      let flickerInterval = setInterval(() => {
        document.title = document.title === '新数据提醒' ? originalTitle : '新数据提醒';
      }, 1000);

      // 停止闪烁，恢复原来的标题
      setTimeout(() => {
        clearInterval(flickerInterval);
        document.title = originalTitle;
      }, 5000);
    },

    // 显示通知
    showNotification(title, message) {
      this.$notify({
        title: title,
        message: message,
        type: 'success', // 类型可以是 'success', 'warning', 'info', 'error'
        duration: 5000 // 通知显示时长（毫秒）
      });

      // 新增语音提示
      if (message === '都是链接') {
        this.playVoiceNotification('新订单已新增，注意查收');
      }
    },

    // 播放语音提示
    playVoiceNotification(text) {
      const utterance = new SpeechSynthesisUtterance(text);
      utterance.lang = 'zh-CN'; // 设置为中文
      utterance.volume = 1; // 音量
      utterance.rate = 1; // 语速
      utterance.pitch = 1; // 音调
      speechSynthesis.speak(utterance);
    },


    getDefaultDate() {
      // 获取当天日期，并以 yyyy-MM-dd 格式返回
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    /**更改创建时间格式 */
    formatTimestamp(timestamp) {
      if (!timestamp) {
        return '';
      }
      const date = new Date(timestamp);
      const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      return formattedDate;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        uid: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.dateInfo = ''; // 或者设置为 null
      this.handleQuery();
    }
    ,
  }
};
</script>
